package com.sensePlusVR.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.sensePlusVR.utils.MyLog;

/**
 * 
 * @author: Loren
 * @create: 2017-7-24下午3:33:10
 * @desc: 
 * 由于Home键静态注册无法检测到广播，所以动态注册
 * 在检测强制升级分别在GameFragment(相当于在MainActivity中注册，只有MainActivity销毁才会取消注册)中和LoginActivity中注册
 */
public class HomeListener {
	private static final String TAG = HomeListener.class.getSimpleName();
	public static boolean isHomeClick;
    public HomeListener(Context context) {
        mContext = context;
        mHomeBtnReceiver = new HomeBtnReceiver( );
        mHomeBtnIntentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    }

    public void setOnHomeBtnPressListener( OnHomeBtnPressLitener onHomeBtnPressListener ){
        mOnHomeBtnPressListener = onHomeBtnPressListener;
    }

    public void start( ){
        mContext.registerReceiver( mHomeBtnReceiver, mHomeBtnIntentFilter );
    }

    public void stop( ){
        mContext.unregisterReceiver( mHomeBtnReceiver );
    }

    public static class HomeBtnReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            receive( context, intent );
        }
    }

    private static void receive(Context context, Intent intent){
    	MyLog.d(TAG, "receive home...");
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra( "reason" );
            if (reason != null) {
                    if( reason.equals( "homekey" ) ){
                    	isHomeClick = true;
                        // 按Home按键
                    	 if( null != mOnHomeBtnPressListener ){
                    		 mOnHomeBtnPressListener.onHomeBtnPress( );
                    	 }
                    }else if( reason.equals( "recentapps" ) ){
                        // 长按Home按键
                    	 if( null != mOnHomeBtnPressListener ){
                    		 mOnHomeBtnPressListener.onHomeBtnLongPress( );
                    	 }
                    }
            }
        }
    }

    public interface OnHomeBtnPressLitener{
        public void onHomeBtnPress();
        public void onHomeBtnLongPress();
    }

    private Context mContext = null;
    private IntentFilter mHomeBtnIntentFilter = null;
    private static OnHomeBtnPressLitener mOnHomeBtnPressListener = null;
    private HomeBtnReceiver mHomeBtnReceiver = null;
}
